#pragma once
#include<vector>
#include<unordered_set>
#include<unordered_map>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;

class MST {
private:
	struct Cmp {
		bool operator()(const vector<int>& left, const vector<int>& right) {
			return left[2] > right[2];
		}
	};

	int findParent(int x, vector<int>& parents) {
		return x == parents[x] ? x : (parents[x] = findParent(parents[x], parents));
	}

	void merge(int x, int y, vector<int>& parents) {
		int px = parents[x];
		int py = parents[y];
		if (px != py)
			parents[px] = py;
	}
public:
	/*
	Kruskal
	input
		edges: [[u, v, w], ...]   Undirected Connected graph
		n: the number of points
		minCost: the minimum cost
	output
		the one of MST
	*/
	vector<vector<int>> findMST_Kruskal(vector<vector<int>> edges, int n, int& minCost) {
		sort(edges.begin(), edges.end(), [](const vector<int>& left, const vector<int>& right) {
			return left[2] < right[2];
			});
		vector<int>parents(n);
		for (int i = 0; i < n; ++i)
			parents[i] = i;
		vector<vector<int>>tree;
		minCost = 0;
		for (auto& edge : edges) {
			int pu = findParent(edge[0], parents);
			int pv = findParent(edge[1], parents);
			if (pu == pv) continue;
			merge(edge[0], edge[1], parents);
			tree.push_back(edge);
			minCost += edge[2];
		}
		return tree;
	}
	/*
	Prim
	input
		edges: [[u, v, w], ...]  Undirected Connected graph
		n: the number of points
		minCost: the minimum cost
	output
		the one of MST
	*/
	vector<vector<int>> findMST_Prim(vector<vector<int>> edges, int n, int& minCost) {
		unordered_map<int, vector<vector<int>>>graph;
		for (auto edge : edges) {
			graph[edge[0]].push_back(edge);
			swap(edge[0], edge[1]);
			graph[edge[0]].push_back(edge);
		}
		priority_queue<vector<int>, vector<vector<int>>, Cmp>queue;
		unordered_set<int>visited;
		vector<vector<int>>tree;
		minCost = 0;
		int from = 0;
		visited.insert(from);
		while (true) {
			for (auto& edge : graph[from]) {
				if (visited.find(edge[1]) != visited.end()) continue;
				queue.push(edge);
			}
			if (queue.empty()) break;
			auto edge = queue.top();
			queue.pop();
			if (visited.find(edge[1]) != visited.end()) continue;
			minCost += edge[2];
			visited.insert(edge[1]);
			tree.push_back(edge);
			from = edge[1];
		}
		return tree;
	}
};

//int main() {
//	vector<vector<int>> edges = { {0,3,4},{0,1,1},{0,2,1},{2,3,2},{1,3,1},{1,2,2} };
//	int n = 4;
//	MST mst;
//	int minCost = 0;
//	auto tree = mst.findMST_Prim(edges, n, minCost);
//	cout << "minCost" << minCost << endl;
//	for (auto& edge : tree)
//		cout << edge[0] << " " << edge[1] << " " << edge[2] << endl;
//}
